package com.wuwei.elearning.question.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.question.dao.DataDAO;
import com.wuwei.elearning.question.domain.Question;
import com.wuwei.elearning.question.domain.Subject;
import com.wuwei.elearning.question.listener.UploadDataListener;
import com.wuwei.elearning.question.mapper.QuestionMapper;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.service.QuestionService;
import com.wuwei.elearning.question.vo.EChartsPieVo;
import com.wuwei.elearning.utils.RecordUtils;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import com.wuwei.elearning.vo.PageDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 保存题目信息的表，不管是机型题，基础执照题，还是英语题，都保存在该表中 前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-01-20
 */
@RestController
@Slf4j
@RequestMapping("/elearning/question")
@CrossOrigin
public class QuestionController {

    @Resource
    private QuestionMapper questionMapper;



    @Resource
    private SubjectMapper subjectMapper;
    @Autowired
    private QuestionService questionService;

    @GetMapping("getById/{id}")
    public Result<Question> getById(@PathVariable("id") Long id){
        Question question = questionMapper.selectById(id);
        return Result.ok(question);
    }

    @GetMapping("statisticsBySubjectId/{subjectId}")
    public Result<List<EChartsPieVo>> statisticsBySubjectId(@PathVariable("subjectId") Long subjectid){
        //根据subjectid查询其所有子孙节点
        List<Subject> subjects = subjectMapper.getLeafsById(subjectid);
        List<EChartsPieVo> EChartsPieVos = new ArrayList<>();
        for (Subject subject : subjects) {
            Long id = subject.getId();
            Long count = questionMapper.selectCount(new LambdaQueryWrapper<Question>().eq(Question::getSubjectId, id));
            EChartsPieVo EChartsPieVo = new EChartsPieVo();
            EChartsPieVo.setValue(count);
            EChartsPieVo.setId(id);
            EChartsPieVo.setName(subject.getName());
            EChartsPieVos.add(EChartsPieVo);
        }
        return Result.ok(EChartsPieVos);
    }

    @GetMapping("statistics/all")
    public Result<List<EChartsPieVo>> statisticsAll(){
        //所有基础执照题目的主键
        //根据subjectid查询其所有子孙节点
        List<EChartsPieVo> EChartsPieVos = new ArrayList<>();
        for (long id : Constant.SUBJECTIDS) {
            List<Long> subjectIds = subjectMapper.getSonsById(id);
            Subject subject = subjectMapper.selectById(id);
            String name = subject.getName();
            EChartsPieVo EChartsPieVo = new EChartsPieVo();
            EChartsPieVo.setId(id);
            EChartsPieVo.setName(name);
            Long count;
            if (!subjectIds.isEmpty()) {
                count = questionMapper.selectCount(new LambdaQueryWrapper<Question>().in(Question::getSubjectId, subjectIds));
            } else {
                count = 1L;
            }
            EChartsPieVo.setValue(count);
            EChartsPieVos.add(EChartsPieVo);
        }
        return Result.ok(EChartsPieVos);
    }

    @PostMapping("update")
    public Result<String> update(@RequestBody Question question,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        questionService.updateQuestion(question,account);
        return Result.ok("中文版本题目修改成功！");
    }

    @GetMapping("list/{name}/{currentPage}/{pageSize}")
    public Result<List<Question>> list(@PathVariable("name") String name,
                                       @PathVariable("currentPage") int currentPage,
                                       @PathVariable("pageSize") int pageSize,
                                       @RequestParam(value = "subjectId", required = false) Integer subjectId) {

        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"_".equals(name), Question::getQuestion, name);
        if (subjectId!=null) {
            List<Long> subjectIds = subjectMapper.getSonsById(Long.valueOf(subjectId));
            if (!subjectIds.isEmpty()) {
                wrapper.in(Question::getSubjectId, subjectIds);
            }
        }


        IPage<Question> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<Question> questionIPage = questionMapper.selectPage(page, wrapper);
        List<Question> questions = questionIPage.getRecords();
        return Result.ok(questions);
    }

    /**
     * 查询question表中subjectId字段在subject表中找不到的数据
     * @param name
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("noSubjectList/{name}/{currentPage}/{pageSize}")
    public Result<List<Question>> noSubjectList(@PathVariable("name") String name,
                                       @PathVariable("currentPage") int currentPage,
                                       @PathVariable("pageSize") int pageSize) {
        int offset = (currentPage - 1) * pageSize;
        List<Question> questions = questionMapper.noSubjectList(offset,pageSize,name);
        return Result.ok(questions);
    }

    @GetMapping("getTotal/{name}")
    public Result<Long> getTotal(@PathVariable("name") String name,
                                 @RequestParam(value = "subjectId", required = false) Integer subjectId) {
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"_".equals(name), Question::getQuestion, name);
        if (subjectId!=null) {
            List<Long> subjectIds = subjectMapper.getSonsById(Long.valueOf(subjectId));
            if (!subjectIds.isEmpty()) {
                wrapper.in(Question::getSubjectId, subjectIds);
            }
        }

        Long count = questionMapper.selectCount(wrapper);
        return Result.ok(count);
    }

    /**
     * 查询question表中subjectId字段在subject表中找不到的数据
     * @param name
     * @param subjectId
     * @return
     */
    @GetMapping("noSubjectTotal/{name}")
    public Result<Long> noSubjectTotal(@PathVariable("name") String name,
                                 @RequestParam(value = "subjectId", required = false) Integer subjectId) {
        Long count = questionMapper.noSubjectTotal(name);
        return Result.ok(count);
    }

    /**
     * 条件查询
     * @return
     */
    @PostMapping("listBySubject")
    public Result<List<Question>> listBySubject(@RequestBody PageDto pageDto){
        String question = pageDto.getQuestion();
        Long[] subject = pageDto.getSubject();
        int currentPage = pageDto.getCurrentPage();
        int pageSize = pageDto.getPageSize();
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(subject.length>0,Question::getSubjectId,subject)
                .like(Question::getQuestion,question);
        IPage<Question> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<Question> questionIPage = questionMapper.selectPage(page, wrapper);
        List<Question> questions = questionIPage.getRecords();
        return Result.ok(questions);
    }

    @PostMapping("totalBySubject")
    public Result<Long> totalBySubject(@RequestBody PageDto pageDto){
        String question = pageDto.getQuestion();
        Long[] subject = pageDto.getSubject();
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(subject.length>0,Question::getSubjectId,subject)
                .like(Question::getQuestion,question);
        Long count = questionMapper.selectCount(wrapper);
        return Result.ok(count);
    }

    @PostMapping("add")
    public Result<String> add(@RequestBody Question question,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        question.setCreatedBy(account);
        question.setCreatedTime(LocalDateTime.now());
        questionMapper.insert(question);
        return Result.ok("添加成功！");
    }

    @DeleteMapping("delete/{id}")
    public Result<String> delete(@PathVariable("id") Long id){
        questionMapper.deleteById(id);
        return Result.ok("删除成功！");
    }

    @PostMapping("upload")
    public Result<String> file(@RequestParam("file") MultipartFile file,
                               @RequestParam("subjectId") Long subjectId,  // 添加 subjectId 参数
                               HttpServletRequest request) {
        if (file.getSize() != 0) {
            String token = request.getHeader("Authorization");
            Long account = TokenUtil.getAccountFromToken(token);
            try {
                InputStream inputStream = file.getInputStream();
                // 将 subjectId 传递给 service 层
                questionService.upload(inputStream, account, subjectId);
                return Result.ok("上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                return Result.fail(e.getMessage());
            }
        } else {
            return Result.fail("您没有上传任何文件");
        }
    }

    @GetMapping("getBySubjectId")
    public Result<List<Question>> getBySubjectId(@RequestParam Long id,@RequestParam String name,
                                                 @RequestParam Integer currentPage,@RequestParam Integer pageSize
    ){
        Subject subject = subjectMapper.selectById(id);
        String subjectName = subject.getName();
        String substring = subjectName.substring(subjectName.lastIndexOf(" ") + 1);
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Question::getSubjectId,subject);
        IPage<Question> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<Question> questionIPage = questionMapper.selectPage(page, wrapper);
        List<Question> questions = questionIPage.getRecords();
        return Result.ok(questions);
    }

    @GetMapping("getCountBySubjectId")
    public Result<Long> getCountBySubjectId(@RequestParam Long id,@RequestParam String name){
        Subject subject = subjectMapper.selectById(id);
        String subjectName = subject.getName();
        String substring = subjectName.substring(subjectName.lastIndexOf(" ") + 1);
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Question::getSubjectId,subject);
        Long count = questionMapper.selectCount(wrapper);
        return Result.ok(count);
    }

    /**
     * 获取下载文件的模板
     */
    @GetMapping("getTemplate")
    public void getTemplate(HttpServletResponse response){
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"template.xlsx\"");
        String filePath = "template.xlsx";
        try(InputStream inputStream = new FileInputStream(filePath);
            OutputStream outputStream = response.getOutputStream()){
            // 将文件的内容以流的形式写入响应对象
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}

